package com.skyline.courier.rpc;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.skyline.common.reflection.MethodUtils;
import com.skyline.courier.net.Client;
import com.skyline.courier.net.Connection;
import com.skyline.courier.rpc.annotation.ServiceAccessor;
import com.skyline.courier.rpc.exception.RpcGenerateException;
import com.skyline.courier.rpc.pojo.RequestBean;

/**
 * 客户端方法拦截器
 * 
 * @author wuqh
 * 
 */
public class ServiceAccessorInterceptor implements MethodInterceptor {
	private static final Logger LOGGER = LoggerFactory.getLogger(ServiceAccessorInterceptor.class);
	private final Set<Method> USER_DECLARED_METHODS = new HashSet<Method>(16);
	private final String serviceName;
	private final Client client;

	public ServiceAccessorInterceptor(Class<?> clazz, Client client) throws RpcGenerateException {
		ServiceAccessor accessor = clazz.getAnnotation(ServiceAccessor.class);

		this.serviceName = getServiceName(clazz, accessor);
		this.client = client;

		try {
			detectProxyMethod(clazz);
		} catch (Exception e) {
			throw new RpcGenerateException(e);
		}
	}

	private String getServiceName(Class<?> clazz, ServiceAccessor proxy) {
		if (proxy != null && StringUtils.isNotBlank(proxy.value())) {
			return StringUtils.trim(proxy.value());
		} else {
			return clazz.getName();
		}
	}

	/**
	 * 检测类中的自定义方法
	 * 
	 * @param clazz
	 * @throws Exception
	 */
	private void detectProxyMethod(Class<?> clazz) throws Exception {
		MethodUtils.doWithMethods(clazz, new MethodUtils.MethodCallback() {

			@Override
			public void doWith(Method method) throws Exception {
				USER_DECLARED_METHODS.add(method);
			}
		}, MethodUtils.USER_DECLARED_METHODS);
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {

		if (USER_DECLARED_METHODS.contains(method)) {
			return doInvokeRemote(method, args);
		}

		return null;
	}

	private Object doInvokeRemote(Method method, Object[] args) throws Throwable {
		Connection connection = null;
		try {
			connection = client.connect();
		} catch (IOException e) {
			LOGGER.error("无法获取远程连接", e);
			throw e;
		}

		RequestBean requestBean = new RequestBean();
		requestBean.setServiceName(serviceName);
		requestBean.setMethodName(method.getName());
		requestBean.setArgs(args);

		try {
			return connection.send(requestBean);
		} catch (IOException e) {
			LOGGER.error("发生消息失败", e);
			throw e;
		}

	}

}
